package com.xiaochong.tir.manager.service;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xiaochong.tir.common.data.mapper.NavigationMapper;
import com.xiaochong.tir.common.data.po.Navigation;
import com.xiaochong.tir.manager.config.druid.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class NavigationService {

	@Autowired
	private NavigationMapper navigationMapper;

	public List<Navigation> getNavigationByParentId(Integer parentId) {
		return navigationMapper.selectByParentId(parentId);
	}

	public PageInfo<Navigation> getNavigationByParent(int pageNum, int pageSize) {
		PageHelper.startPage(pageNum, pageSize);
		return new PageInfo<Navigation>(navigationMapper.selectByParent());
	}

	public List<JSONObject> getAllNavigation() {
		List<Navigation> parents = navigationMapper.selectByParent();
		// 设置父节点ID与索引下标的对应关系
		Map<Integer, Integer> map = new HashMap<>();
		for (int i = 0; i < parents.size(); i++) {
			Navigation navigation = parents.get(i);
			map.put(navigation.getId(), i);
		}
		// 将子节点添加到对应的父节点
		List<Navigation> childrens = navigationMapper.selectByChildren();
		for (Navigation navigation : childrens) {
			Integer parentId = navigation.getParentId();
			if (parentId == null || parentId == 0) {
				continue;
			}
			int index = map.get(parentId);
			parents.get(index).addChildren(navigation);
		}
		// 将导航节点转换为JSON
		List<JSONObject> list = new ArrayList<>();
		for (Navigation navigation : parents) {
			list.add(navigation.toJSONObject());
		}
		return list;
	}

	@Operation
	@Transactional
	public int addNavigation(Navigation navigation) {
		return navigationMapper.insertSelective(navigation);
	}

	@Operation
	@Transactional
	public int updateByPrimaryKey(Navigation navigation,Navigation oldNavigation) {
		return navigationMapper.updateByPrimaryKey(navigation);
	}

	@Operation
	@Transactional
	public int deleteNavById(Integer id,Navigation old) {
		return navigationMapper.deleteByPrimaryKey(id);
	}

	@Operation
	@Transactional
	public int deleteNavByParentId(Integer navId, Navigation old) {
		return navigationMapper.deleteNavByParentId(navId);
	}

	public List<Navigation> selectByEntityList(Navigation navigation) {
		return navigationMapper.selectByEntityList(navigation);
	}

	public Navigation selectByPrimaryKey(Integer id) {
		return navigationMapper.selectByPrimaryKey(id);
	}

	/**
	 * 根据条件查询单条记录
	 * @param entity
	 */
	public Navigation selectByEntity(Navigation entity) {
		return this.navigationMapper.selectByEntity(entity);
	}
}
